<template>
  <!-- 运营系统-短剧列表 -->
  <d2-container class="d-flex flex-column mod-sys__user">
    <template v-if="$hasPermission('playlet:playletEpisodes:index')">
      <el-dialog
        class="innerDialog"
        v-dialogDrag
        :close-on-click-modal="false"
        width="500px"
        :title="(playTitle || '') + '  下载进度'"
        :visible.sync="innerDownloadVisible"
        append-to-body
      >
        <div class="d-flex flex-column mr-10">
          <div class="d-flex mb-5" style="font-size: 15px">
            下载中，请稍后...
          </div>
          <el-progress
            :text-inside="false"
            :stroke-width="18"
            text-color="#409eff"
            :percentage="downloadPercentage"
          ></el-progress>
          <div style="height: 30px"></div>
        </div>
      </el-dialog>
      <el-dialog
        class="innerVideoDialog"
        v-dialogDrag
        @close="closeVideoDialogFn"
        width="650px"
        :title="playTitle || '视频'"
        :visible.sync="innerPlayVisible"
        append-to-body
      >
        <div class="playerMain">
          <d-player
            class="dplayer"
            :options="videoOptions"
            ref="player"
          ></d-player>
        </div>
      </el-dialog>
      <div class="d-flex" slot="header">
        <el-form
          class="d-flex b-s my-10"
          :inline="true"
          size="small"
          :model="dataForm"
          @keyup.enter.native="getTableList()"
        >
          <el-form-item label="小程序名称">
            <el-input
              v-model="dataForm.keyword"
              placeholder="小程序名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="集数">
            <el-input
              v-model="dataForm.name"
              @input="(v) => (dataForm.name = handleNumber1(v))"
              placeholder="集数,请输入数字"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-search"
              type="primary"
              @click="getTableList()"
              >查询</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button
              type="success"
              icon="el-icon-circle-plus-outline"
              v-show="$hasPermission('playlet:playletEpisodes:create')"
              @click="addOrUpdateData()"
              >添加剧集</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="d-flex h-100 b-s flex-column">
        <div class="d-flex flex-1">
          <div class="overflow">
            <vxe-table
              ref="xTable"
              border
              height="100%"
              resizable
              :data="dataList"
              :loading="tableLoading"
              :checkbox-config="{ checkMethod: CheckboxIsDisabled }"
              @checkbox-all="selectAllEvent"
              @checkbox-change="selectChangeEvent"
              :loading-config="{
                icon: 'vxe-icon-indicator roll',
                text: '正在拼命加载中...',
              }"
            >
              <vxe-column
                type="checkbox"
                field="checkbox"
                width="120"
                align="center"
              >
                <template #default="{ row }">
                  <div
                    v-if="typeof row.media_status == 'number'"
                    class="position-absolute top-0 left-0 d-flex w-100 h-100"
                  >
                    <div
                      v-if="
                        row.media_status == 1 ||
                        row.media_status == 3 ||
                        row.is_upload == 2 ||
                        row.is_upload == 3
                      "
                      class="d-flex w-100 a-center j-center"
                    >
                      <div
                        class="w-90 py-5 rounded-40"
                        :class="row.is_upload == 1 ? 'warnTag' : 'successTag'"
                        style="font-size: 14px"
                      >
                        {{
                          row.media_status == 0
                            ? row.is_upload_name
                            : row.media_status_name
                        }}
                      </div>
                    </div>
                  </div>
                </template>
              </vxe-column>

              <vxe-column
                width="100"
                field="id"
                title="id"
                sortable
                align="center"
              ></vxe-column>
              <vxe-column
                width="180"
                field="playlet_name"
                title="短剧名称"
                align="center"
              ></vxe-column>
              <vxe-column
                width="180"
                field="play_url"
                title="在线预览"
                align="center"
              >
                <template #default="{ row }">
                  <a
                    class="preview pointer"
                    style="color: #1389ff"
                    @click.stop="previewVideoFn(row)"
                    >预览</a
                  >
                </template>
              </vxe-column>
              <vxe-column
                width="150"
                field="cover"
                title="封面图片"
                align="center"
              >
                <template #default="{ row }">
                  <img
                    class="pointer"
                    width="80"
                    height="auto"
                    :src="row.cover"
                    @click.stop="previewPicFn(row)"
                  />
                </template>
              </vxe-column>
       
              <vxe-column
                width="150"
                field="playlet_number"
                title="集数"
                align="center"
              ></vxe-column>
      
            
              <vxe-column
                width="150"
                field="created_at"
                title="创建时间"
                align="center"
              ></vxe-column>
              <vxe-column
                width="160"
                field="updated_at"
                title="修改时间"
                sortable
                cell-type="string"
                align="center"
              ></vxe-column>

              <vxe-column title="操作" width="200" align="center" fixed="right">
                <template #default="{ row }">
                  <el-button
                    size="medium"
                    round
                    icon="el-icon-edit"
                    v-show="$hasPermission('playlet:playletEpisodes:update')"
                    @click="addOrUpdateData(row)"
                    type="primary"
                    >修改</el-button
                  >
                  <!-- <el-button
                    size="medium"
                    round
                    icon="el-icon-edit"
                    v-show="$hasPermission('playlet:playletEpisodes:update')"
                    @click="selecttag(row)"
                    type="primary"
                    >标签</el-button
                  > -->
                  <el-button
                    size="medium"
                    round
                    icon="el-icon-edit"
                    v-show="$hasPermission('playlet:playletEpisodes:delete')"
                    @click="deleteHandleSetter(row)"
                    type="primary"
                    >删除</el-button
                  >
                </template>
              </vxe-column>

              <template #empty>
                <div class="d-flex flex-row a-center j-center font-md">
                  <div class="d-flex">暂时没有充值模板~</div>
                </div>
              </template>
            </vxe-table>
          </div>
        </div>
      </div>
      <!-- 分页 -->
      <div class="d-flex" slot="footer">
        <vxe-pager
          background
          size="medium"
          align="right"
          :border="false"
          :current-page="dataForm.page"
          :page-size="dataForm.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100, 150, 200]"
          :layouts="[
            'PrevPage',
            'Number',
            'NextPage',
            'Sizes',
            'FullJump',
            'Total',
          ]"
          @page-change="handlePageChange"
        >
        </vxe-pager>
      </div>
      <!-- 新增/修改弹窗 -->
      <episodes-add-or-update
        v-if="addOrUpdateVisible"
        ref="addOrUpdateDialog"
        @refreshDataList="getTableList"
      ></episodes-add-or-update>

      <!-- Form -->

      
     


      <!-- 播放视频弹窗 -->
      <play-video v-if="videoVisible" ref="videoDialog"></play-video>
      <!-- 图片预览弹窗 -->
      <pic-preview v-if="picVisible" ref="picDialog"></pic-preview>
      <el-dialog
        title="重要提示"
        class="checkTipDialog"
        :visible.sync="checkTipVisible"
        width="600px"
        center
      >
        <span>{{ examineType == 1 ? "微信" : "抖音" }}已选列表：</span>
        <ul class="data-list">
          <li
            v-for="(item, index) in records"
            :key="index"
            @click.stop="openVideo(item)"
          >
            {{ item.playlet_name + " " + item.playlet_number_name }}
          </li>
        </ul>
        <span slot="footer" class="dialog-footer">
          <el-button class="mr-10" @click="checkTipVisible = false"
            >取 消</el-button
          >
          <el-button class="ml-10" type="primary" @click="submitExamine()"
            >提交{{ examineType == 1 ? "微信" : "抖音" }}审核</el-button
          >
        </span>
      </el-dialog>
    </template>
    <template v-else>
      <div class="d-flex a-center j-center h-100 b-s flex-column">
        <img
          class="d-flex mb-10"
          :src="permissionBase64"
          alt="没有访问权限"
          style="width: 300px"
        />
        <div class="d-flex">抱歉，您没有访问权限</div>
      </div>
    </template>
  </d2-container>
</template>

<script>
let that;
import { mapState, mapMutations } from "vuex";
import { handleNumber1 } from "@/libs/validate";
import mixinViewModule from "@/mixins/view-module";
import EpisodesAddOrUpdate from "./playletEpisodes-add-or-update";
import PlayVideo from "./playVideo";
import PicPreview from "./picPreview";
import * as clipboard from "clipboard-polyfill";
import VueDPlayer from "@/libs/vue-dplayer";
import { gettagList } from "../../api/index"
require("/src/assets/style/vue-dplayer.css");
export default {
  mixins: [mixinViewModule],
  components: {
    "d-player": VueDPlayer,
    EpisodesAddOrUpdate,
    PlayVideo,
    PicPreview,
  },
  data() {
    return {
      diy_dialogFormVisible:false,
       diyform: {
          name: '',
          region: '',
          date1: '',
          date2: '',
          delivery: false,
          type: [],
          resource: '',
          desc: ''
        },
        formLabelWidth: '120px',
      selecttagDialog:false,
      permissionBase64:
        "",
      tableLoading: false,
      handleNumber1,
      curent: 0,
      total: 0,
      curName: "",
      innerPlayVisible: false,
      records: [],
      checkIDArray: [],
      checkTipVisible: false,
      dataForm: {
        page: 1,
        pageSize: 10,
        keyword: "", //搜索
      },
      videoVisible: false,
      picVisible: false,
      // 增改
      addOrUpdateVisible: false,
      roleVisible: false,
      dataList: [],
      customColumns: [],
      playTitle: "",
      innerDownloadVisible: false, //是否显示下载视频进度
      downloadPercentage: 0,
      examineType: 1, //1微信，2抖音
      videoOptions: {
        video: {
          url: "", //视频链接
          pic: "", //封面图
          thumbnails: "", //缩略图
        },
        theme: "#409eff", //主题色
        screenshot: true, //是否支持截图
        autoplay: true, //是否自动播放
        preload: "auto", //预加载
        contextmenu: [
          {
            text: "下载视频",
            click: (e) => {
              this.downloadVideo();
            },
          },
          {
            text: "复制视频地址",
            click: (e) => {
              if (this.videoOptions.video.url) {
                this.copyText(this.videoOptions.video.url);
                return;
              }
              this.$message({
                message: "复制失败！视频地址为空！",
                type: "error",
                duration: 1500,
              });
            },
          },
        ],
      },
    };
  },
  created() {
    if (this.$hasPermission("playlet:playletEpisodes:index")) {
      this.getTableList();
      console.log(window);
    }
  },
  watch: {},
  mounted() {
    that = this;
  },
  computed: {
    ...mapState("d2admin/user", ["info"]),
  },
  methods: {
    ...mapMutations({
      pageInit: "d2admin/page/init",
      headerSet: "d2admin/menu/headerSet",
    }),
 
    async selecttag(e){
      console.log(483,e.id)
      let data =  await this.$axios.get( `/api/playlet/playlet/tag/${e.id}`)
      console.log(483,data)
      this.selecttagDialog = !this.selecttagDialog;
    },
    showselecttag(str){
      if(str == 't'){
        console.log('点击了确认')
      }else{
        
          console.log('点击了取消')
        }
        this.selecttagDialog = !this.selecttagDialog;
    },
    gettagdata(){

    },
    //预览视频
    previewVideoFn(row) {
      this.videoVisible = true;
      this.$nextTick(() => {
        this.$refs.videoDialog.update(
          row.play_url,
          row.playlet_name + "  " + row.playlet_number_name,
          row.cover
        );
      });
    },
    //预览图片
    previewPicFn(row) {
      this.picVisible = true;
      this.$nextTick(() => {
        this.$refs.picDialog.update(
          row.cover,
          row.playlet_name + "  " + row.playlet_number_name + " 封面图"
        );
      });
    },
    CheckboxIsDisabled({ row }) {
      // console.log(row);
      return (
        (row.media_status == 0 ||
          row.media_status == 2 ||
          row.media_status == 4) &&
        (row.is_upload == 1 || row.is_upload == 4)
      );
    },
    copyText(text) {
      console.log(text);
      clipboard.writeText(text).then(
        function () {
          that.$message({
            message: "复制成功！",
            type: "success",
            duration: 1500,
          });
        },
        function () {
          that.$message({
            message: "复制失败！",
            type: "error",
            duration: 1500,
          });
        }
      );
    },
    closeVideoDialogFn() {
      this.player = this.$refs.player.dp;
      console.log(this.player);
      if (this.player) {
        this.player.pause();
        this.player.seek(0);
      }
    },
    selectAllEvent({ checked }) {
      this.records = this.$refs.xTable.getCheckboxRecords();
      this.checkIDArray = this.records.map((element) => element.id);
      console.log(this.checkIDArray);
    },
    selectChangeEvent({ checked }) {
      this.records = this.$refs.xTable.getCheckboxRecords();
      this.checkIDArray = this.records.map((element) => element.id);
      console.log(this.checkIDArray);
    },
    openVideo(row) {
      console.log(row);
      this.playTitle = row.playlet_name + ("  " + row.playlet_number_name);
      this.innerPlayVisible = true;
      this.videoOptions.video.url = row.play_url;
      this.videoOptions.video.pic = row.cover;
      this.$nextTick(() => {
        if (!this.player) {
          this.player = this.$refs.player.dp;
        }
        this.player.switchVideo({
          url: row.play_url,
          pic: row.cover,
        });
        setTimeout(() => {
          this.player.play();
        }, 100);
      });
    },
    // 检查勾选
    // async checkExamine(type) {
    //   this.examineType = type;
    //   console.log(this.checkIDArray.length);
    //   if (!this.checkIDArray.length) {
    //     return this.$message({
    //       message: "请先勾选下面的剧集！",
    //       type: "error",
    //       duration: 1500,
    //     });
    //   }
    //   this.checkTipVisible = true;
    // },
    async submitExamine() {
      this.checkTipVisible = false;
      const examineRes = await this.$axios.post(
        "/api/playlet/episodes/examine",
        {
          ids: this.checkIDArray,
          type: this.examineType,
        }
      );
      this.$refs.xTable.clearCheckboxRow();
      if (Array.isArray(examineRes)) {
        if (examineRes.length) {
          let examineError = "";
          for (var i = 0; i < examineRes.length; i++) {
            if (examineRes[i]) {
              examineError += examineRes[i];
            }
          }
          that.$message({
            message: examineError,
            type: "error",
            duration: examineRes.length > 10 ? 6000 : 3000,
          });
        }
      }
      console.log(examineRes);
    },
    async getTableList() {
      this.tableLoading = true;
	  if(this.dataForm.keyword!='' || this.dataForm.name!='' ){
	  	this.dataForm.page = 1
	  }
      const tableRes = await this.$axios.get(
        "/api/playlet/episodes?" + this.$qs.stringify(this.dataForm)
      );
      this.tableLoading = false;
      this.dataList = tableRes.data;
      console.log(this.dataList);
      this.total = tableRes.total;
      this.$nextTick(() => {
        console.log(window);
      });
    },
    async downloadVideo() {
      this.innerDownloadVisible = true;
      if (this.downloadPercentage != 0) {
        that.$message({
          message: `请等待${this.playTitle}下载完`,
          type: "error",
          customClass: "messageClass",
          duration: 2000,
        });
        this.innerDownloadVisible = true;
        return;
      }
      let play_url = this.videoOptions.video.url.replace("http://", "https://"),
        download_name = this.playTitle;
      try {
        let x = new XMLHttpRequest();
        x.open("GET", play_url, true);
        x.addEventListener(
          "progress",
          function (evt) {
            if (evt.lengthComputable) {
              let percentComplete = evt.loaded / evt.total;
              that.downloadPercentage = Math.floor(percentComplete * 100);
              if (that.downloadPercentage == 100) {
                that.innerDownloadVisible = false;
                that.downloadPercentage = 0;
                that.$message({
                  message: `${that.playTitle || "视频"}下载成功！`,
                  type: "success",
                  duration: 2000,
                });
              }
            }
          },
          false
        );
        x.responseType = "blob";
        x.onload = function (e) {
          //会创建一个 DOMString，其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
          let url = window.URL.createObjectURL(x.response),
            a = document.createElement("a");
          a.href = url;
          a.download = download_name;
          a.click();
          a.remove();
        };
        x.send();
      } catch (error) {
        that.innerDownloadVisible = false;
        that.downloadPercentage = 0;
        that.$message({
          message: "下载视频失败！",
          type: "error",
          duration: 2000,
        });
        console.error(error);
      }
    },
    //新增/修改弹窗
    async addOrUpdateData(row) {
      console.log(row);
      this.addOrUpdateVisible = true;
      if (typeof row == "object" && row != null) {
        // this.curName = row.real_name;
        const id = row.id;
        const userRes = await this.$axios.get(
          `/api/playlet/episodes/update/${id}`,
          {}
        );
        this.$nextTick(() => {
          this.$refs.addOrUpdateDialog.playTitle =
            row.playlet_name + "  " + row.playlet_number_name;
          this.$refs.addOrUpdateDialog.playId = id;
          this.$refs.addOrUpdateDialog.update(userRes);
        });
      } else {
        this.$nextTick(() => {
          this.$refs.addOrUpdateDialog.playId = null;
          this.$refs.addOrUpdateDialog.init();
        });
      }
    },
    // 删除
    deleteHandleSetter(row) {
      this.$confirm(
        this.$t("public.prompt.info", {
          handle: this.$t("views.public.delete"),
        }),
        this.$t("public.prompt.title"),
        {
          confirmButtonText: this.$t("views.public.confirm"),
          cancelButtonText: this.$t("views.public.cancel"),
          type: "warning",
        }
      )
        .then(() => {
          this.$axios
            .delete(`/api/playlet/episodes/delete/${row.id}`, {})
            .then((res) => {
              this.$message({
                message: this.$t("views.public.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.getTableList();
                },
              });
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.successTag {
  background-color: #caf0ba;
  color: #376f1f;
}
.warnTag {
  background-color: #fff1dc;
  color: #e6a23c;
}
.checkTipDialog :deep(.el-dialog__body) {
  padding: 5px 25px 0px 25px;
}
.innerVideoDialog :deep(.el-dialog__body) {
  padding: 0px !important;
}
.dplayer {
  height: 450px;
}

.checkTipDialog {
  .data-list {
    min-height: 200px;
    max-height: 450px;
    overflow-y: auto;
    padding: 0px;
    text-indent: 10px;
    margin: 5px 0px 0px 0px;
    list-style-type: none;

    li {
      cursor: pointer;
      border-radius: 6px;
      padding: 10px 0px 10px 0px;
    }

    li:hover {
      background-color: #f1f1f1;
      color: #409eff;
    }
  }
}

.item {
  .close {
    width: 26px;
    height: 26px;
    border: 2px solid #f76f21;
    border-radius: 26px;

    .close-icon {
      font-size: 20px;
      color: #f76f21;
    }
  }

  .item-title {
    font-size: 22px;
    font-weight: bold;
  }

  .item-simulate {
    border: 6px solid #a3a2a2;
    border-radius: 10px;
    width: 375px;
    min-height: 700px;
    max-height: 1200px;
    margin: 0 auto 10px;
    padding: 10px 5px;

    .list {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      align-items: flex-start;

      .box {
        width: 165px;
        height: 93px;
        background: #f9f8f8;
        border: 2px solid #f5f5f5;
        border-radius: 8px;
        display: flex;
        position: relative;
        flex-direction: column;
        justify-content: flex-end !important;
        padding: 0 !important;
        box-sizing: content-box;
        margin: 10px 0;
        align-items: center;

        .pointer {
          width: 50%;
          height: auto;
          position: absolute;
          bottom: 0;
          right: 0;
        }

        .price {
          font-size: 15px;
          font-weight: 600;
          line-height: 35px;
          margin: 0;

          em {
            font-size: 35px;
            font-style: normal;
          }
        }

        .get {
          width: 100%;
          height: 28px;
          line-height: 28px;
          text-align: center;
          background: linear-gradient(180deg, #fff19d, #ff9e00);
          border-radius: 0 0 5px 5px;
          font-size: 14px;
          color: #583600;
          letter-spacing: 1px;
          font-weight: 500;
          margin: 0;
        }
      }

      .box-normal {
        .price {
          color: #f76f21;
        }

        .get {
          background: #fff7e3;
          color: #bf891c;
        }
      }

      .box-active {
        border: 2px solid #f97d36;
      }
    }
  }
}

</style>
<style>
.el-button--medium.is-round{
  padding: 10px 20px;
    margin: 4px 0;
}
</style>